package com.example.day04;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;

import com.example.day04.bean.MsgEvent;
import com.example.day04.not.MyService;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.io.IOException;

public class MainActivity extends AppCompatActivity {

    private static final int ALBUM_CODE = 100;
    private ProgressBar mPb;
    private TextView mPrText;
    private Button mButton;
    private Button mButton2;
    private ImageView mImageview;
    private ProgressBar mPb1;
    private TextView mPrText1;
    private File mFile;
    private Uri mImageUri;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        EventBus.getDefault().register(this);
        initViews();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void getMsg(MsgEvent msgEvent) {
        mPb1.setMax((int) msgEvent.getMax());
        mPb1.setProgress((int) msgEvent.getProgress());

        float v = (float) msgEvent.getProgress() / msgEvent.getMax();
        float v1 = Math.round(v * 100);
        mPrText1.setText("当前下载进度：" + v1 + "%");
        Log.i("111111", "当前下载进度：" + v1 + "%");
        if ((int) msgEvent.getMax() == (int) msgEvent.getProgress()) {
            Toast.makeText(this, "下载完成", Toast.LENGTH_SHORT).show();
        }
    }

    private void checkPremisstion() {
        //检查 sdcard读权限
        int i = ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
        if (i != PackageManager.PERMISSION_GRANTED) {//没有权限，申请权限
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 100);
        }

    }

    private void initViews() {
        mPb = findViewById(R.id.pb);
        mPrText = findViewById(R.id.pr_text);
        mButton = findViewById(R.id.button);
        mButton2 = findViewById(R.id.button2);
        mImageview = findViewById(R.id.imageView);
        mPb1 = findViewById(R.id.pb1);
        mPrText1 = findViewById(R.id.pr_text1);
    }

    public void onClick(View v) {
        switch (v.getId()) {
            default:
                break;
            case R.id.button2:
                Intent intent = new Intent(this, MyService.class);
                startService(intent);
                break;
            case R.id.bottom:
                takesD();
                break;
        }
    }

    private void takesD() {
        //权限判断
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                == PackageManager.PERMISSION_GRANTED) {
            openAlbum();
        } else {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission
                    .WRITE_EXTERNAL_STORAGE}, 100);
        }
    }

    private void openAlbum() {
        Intent intent = new Intent(Intent.ACTION_PICK);
        intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
        startActivityForResult(intent, ALBUM_CODE);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            if (permissions[0] == Manifest.permission.CAMERA) {
                openCamera();
            } else if (permissions[0] == Manifest.permission.WRITE_EXTERNAL_STORAGE) {
                openAlbum();
            }
        }
    }

    private void openCamera() {
        //创建文件用于保存图片
        mFile = new File(getExternalCacheDir(), System.currentTimeMillis() + ".jpg");
        if (!mFile.exists()) {
            try {
                mFile.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
            mImageUri = Uri.fromFile(mFile);
        } else {
            //第二个参数要和清单文件中的配置保持一致
            mImageUri = FileProvider.getUriForFile(this, "com.baidu.upload.provider", mFile);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == ALBUM_CODE) {
            //相册
            if (resultCode == RESULT_OK) {
                Uri imageUri = data.getData();
                //处理uri,7.0以后的fileProvider 把URI 以content provider 方式 对外提供的解析方法
                File file = getFileFromUri(imageUri, this);

                if (file.exists()) {
                    updateFile(file);
                }
            }
        }
    }

    private void updateFile(File file) {

    }

    private File getFileFromUri(Uri imageUri, MainActivity mainActivity) {
        return null;
    }
}
